package at.fhj.itm11.fotorater.data;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;

import at.fhj.itm11.fotorater.model.Category;
import at.fhj.itm11.fotorater.model.Photo;

@ApplicationScoped
public class PhotoRepository {

	@Inject
	private EntityManager em;

	public Photo findById(Long id) {
		return em.find(Photo.class, id);
	}

	public List<Photo> findAllOrderedByUploadDate(int firstResult, int maxResult) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Photo> criteria = cb.createQuery(Photo.class);
		Root<Photo> photo = criteria.from(Photo.class);

		criteria.select(photo).orderBy(cb.desc(photo.get("uploadDate")));
		TypedQuery<Photo> query = em.createQuery(criteria);
		query.setFirstResult(firstResult);
		query.setMaxResults(maxResult);
		return query.getResultList();
	}
	
	public List<Photo> findAllForCategory(Category category, int firstResult, int maxResult) {		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Photo> criteria = cb.createQuery(Photo.class);
		Root<Photo> photo = criteria.from(Photo.class);
		
		criteria.select(photo).where(cb.equal(photo.get("category"), category));
		TypedQuery<Photo> query = em.createQuery(criteria);
		query.setFirstResult(firstResult);
		query.setMaxResults(maxResult);
		return query.getResultList();
	}
	
	public List<Photo> findAllOrderedByLikes(int firstResult, int maxResult) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Photo> criteria = cb.createQuery(Photo.class);
		Root<Photo> photo = criteria.from(Photo.class);
		
		List<Order> orderings = new ArrayList<Order>();
		orderings.add(cb.desc(photo.get("likes")));
		orderings.add(cb.asc(photo.get("dislikes")));
		
		criteria.select(photo).orderBy(orderings);
		TypedQuery<Photo> query = em.createQuery(criteria);
		query.setFirstResult(firstResult);
		query.setMaxResults(maxResult);
		return query.getResultList();
	}
	
	public List<Photo> findAllOrderedByDislikes(int firstResult, int maxResult) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Photo> criteria = cb.createQuery(Photo.class);
		Root<Photo> photo = criteria.from(Photo.class);
		
		List<Order> orderings = new ArrayList<Order>();
		orderings.add(cb.desc(photo.get("dislikes")));
		orderings.add(cb.asc(photo.get("likes")));
		
		criteria.select(photo).orderBy(orderings);
		TypedQuery<Photo> query = em.createQuery(criteria);
		query.setFirstResult(firstResult);
		query.setMaxResults(maxResult);
		return query.getResultList();
	}

}
